package com.wing.contract.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.JsonResult;
import com.wing.contract.dao.ContractCategoryDao;
import com.wing.contract.model.entity.ContractCategory;
import com.wing.contract.model.request.ContractCategoryForm;
import com.wing.contract.model.response.ContractCategoryVO;
import com.wing.sell.model.response.NodeDataVO;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 合同类型分类-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class ContractCategoryServiceImpl extends ServiceImpl<ContractCategoryDao, ContractCategory> implements ContractCategoryService {

    @Override
    public int add(ContractCategoryForm contractCategoryForm) {

        //校验

        ContractCategory contractCategory =new ContractCategory();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(ContractCategory.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(contractCategoryForm, contractCategory, copyOptions);
        contractCategory.setCreatorName(JwtUtils.getLoginUsername());
        return baseMapper.insert(contractCategory);
    }

    @Override
    public List<ContractCategoryVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<ContractCategoryVO> pageList4app(Page page, Map<String, Object> params) {
        List<ContractCategoryVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public ContractCategoryVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional
    public int enable(Long id) {
        ContractCategoryVO categoryVO=baseMapper.get4appById(id);
        if (categoryVO!=null){
            ContractCategory contractCategory = new ContractCategory();
            contractCategory.setId(id);
            contractCategory.setIsDeleted(true);
            int updateCount=baseMapper.updateById(contractCategory);
            ContractCategory contractCategoryParent = new ContractCategory();
            contractCategoryParent.setId(categoryVO.getParentId());
            contractCategoryParent.setHasEnableChild(true);
            baseMapper.updateById(contractCategoryParent);
            return updateCount;
        }
        return 0;
    }

    @Override
    @Transactional
    public int disable(Long id) {
        ContractCategoryVO categoryVO=baseMapper.get4appById(id);
        if (categoryVO!=null){
            ContractCategory contractCategory = new ContractCategory();
            contractCategory.setId(id);
            contractCategory.setIsDeleted(false);
            int updateCount=baseMapper.updateById(contractCategory);
            int count=baseMapper.selectCount(new QueryWrapper<ContractCategory>().eq("parent_id",contractCategory.getParentId()).eq("is_deleted",true));
            if (count==0){
                ContractCategory contractCategoryParent=new ContractCategory();
                contractCategoryParent.setId(categoryVO.getParentId());
                contractCategoryParent.setHasEnableChild(false);
                baseMapper.updateById(contractCategoryParent);
            }
            return updateCount;
        }

        return 0;
    }

    @Override
    public JsonResult getTreeData(Long selectId, ContractCategory.Type type) {
        Map<String, Object> params = new HashMap<>();
        params.put("isDeleted", 1);
        if(null != type){
            params.put("type", type.getValue());
        }
        List<ContractCategoryVO> list = baseMapper.list4app(params);
        Map<Long,List<NodeDataVO>> map=new HashMap<>();
        for (ContractCategoryVO contractCategoryVO:list) {
            if (map.containsKey(contractCategoryVO.getParentId())){
                NodeDataVO nodeDataVO=new NodeDataVO();
                nodeDataVO.setValue(contractCategoryVO.getId().toString());
                nodeDataVO.setName(contractCategoryVO.getName());
                if(!contractCategoryVO.getIsFinal() || !contractCategoryVO.getIsDeleted()){
                    nodeDataVO.setDisabled(true);
                }
                if(selectId != null && selectId.equals(contractCategoryVO.getId())){
                    nodeDataVO.setSelected(true);
                }
                map.get(contractCategoryVO.getParentId()).add(nodeDataVO);
            }else{
                List<NodeDataVO> tmpList=new ArrayList<>();
                NodeDataVO nodeDataVO=new NodeDataVO();
                nodeDataVO.setValue(contractCategoryVO.getId().toString());
                nodeDataVO.setName(contractCategoryVO.getName());
                if(!contractCategoryVO.getIsFinal() || !contractCategoryVO.getIsDeleted()){
                    nodeDataVO.setDisabled(true);
                }
                if(selectId != null && selectId.equals(contractCategoryVO.getId())){
                    nodeDataVO.setSelected(true);
                }
                tmpList.add(nodeDataVO);
                map.put(contractCategoryVO.getParentId(),tmpList);
            }
        }
        List<NodeDataVO> rootList=map.get(-1L);
        if (rootList==null){
            return JsonResult.success();
        }
        constructTree(rootList,map);
        return JsonResult.success(rootList);
    }

    private void  constructTree(List<NodeDataVO> parentList,Map<Long,List<NodeDataVO>> dataMap){
        for (NodeDataVO node:parentList) {
            Long nodeId=Long.valueOf(node.getValue());
            List<NodeDataVO> childList=dataMap.get(nodeId);
            if (childList!=null){
                node.setChildren(childList);
                constructTree(childList,dataMap);
            }
        }
    }

}
